import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

const expenseTypeMap = {
  material: '材料费',
  labor: '人工费',
  equipment: '设备费',
  other: '其他费用'
} as const;

export async function GET() {
  try {
    // 获取所有支出记录
    const expenses = await prisma.expense.findMany({
      select: {
        type: true,
        amount: true,
        site: {
          select: {
            name: true,
          },
        },
      },
    });

    // 按类型统计总支出
    const expensesByType = expenses.reduce((acc, expense) => {
      acc[expense.type] = (acc[expense.type] || 0) + expense.amount;
      return acc;
    }, {} as Record<string, number>);

    // 转换为图表数据格式
    const pieData = Object.entries(expensesByType).map(([type, amount]) => ({
      name: expenseTypeMap[type as keyof typeof expenseTypeMap],
      value: amount,
    }));

    // 按工地和类型统计
    const expensesBySiteAndType = expenses.reduce((acc, expense) => {
      const siteName = expense.site.name;
      if (!acc[siteName]) {
        acc[siteName] = {
          siteName,
          material: 0,
          labor: 0,
          equipment: 0,
          other: 0,
        };
      }
      acc[siteName][expense.type] += expense.amount;
      return acc;
    }, {} as Record<string, SiteExpenses>);

    const barData = Object.values(expensesBySiteAndType);

    const totalExpenses = Object.values(expensesByType).reduce((a, b) => a + b, 0);

    return NextResponse.json({
      pieData,
      barData,
      expensesByType,
      totalExpenses,
    });
  } catch (error) {
    console.error('获取支出类型数据失败:', error);
    return NextResponse.json(
      { error: '获取支出类型数据失败' },
      { status: 500 }
    );
  }
}

interface SiteExpenses {
  siteName: string;
  material: number;
  labor: number;
  equipment: number;
  other: number;
} 